<?php


namespace App;

use App\server\MsgContent;

/**
 * 解析包数据
 * Class PackMsg
 * @package App
 */
class PackMsg
{
    /**
     * 协议简单一点么好了
     */


    /**
     * 打包
     * pack
     * @param string $data
     * @return string
     * date:2021/12/22
     * time:13:42
     * auth：xyc
     */
    public static function pack(int $type, string $data)
    {
        $type = pack("n", $type);  //2
        $len = pack("N", (strlen($data))); // 4
        return $type . $len . $data;
    }

    /**
     * unPack
     * @param string $data
     * @return object|null
     * date:2021/12/22
     * time:14:16
     * auth：xyc
     */
    public static function unPack(string $data)
    {
        $len = unpack("Nlen", substr($data, 2, 4)); //总共
        $type = unpack("ntype", substr($data, 0, 2));
        if ($len['len']) {
            $data = substr($data, 6, intval($len['len']));
            return new MsgContent(intval($type['type']), $data);
        }
        return null;
    }

}